import { useApi } from '@/composables/useApi'

export interface LoginPwdReq {
  loginType: string
  loginName: string
  loginPwd: string
  authCode: string
  captchaCode: string
}

export interface LoginUserRole {
  name: string
  code: string
}

export interface LoginUserBind {
  id: number
  type: string
  createTime: string
}

export interface LoginUserInfo {
  nickname?: string
  avatarId?: number
  avatarUrl?: string
  type?: string
  token?: string
  phone?: string
  email?: string
  roleCodes?: string[]
  roles?: LoginUserRole[]
  binds?: LoginUserBind[]
}

export interface LoginUserModifyCmd {
  nickname?: string
  avatarId?: number
  avatarUrl?: string
  phone?: string
  email?: string
  captchaCode?: string
}

export interface CaptchaSendCmd {
  type: 'SMS_LOGIN' | 'MODIFY_PHONE' | 'MODIFY_EMAIL'
  target: string
}
export const LoginResourceTypes = [
  { label: '菜单', value: 'MENU', tagType: 'primary' },
  { label: '功能', value: 'FUNCTION', tagType: 'info' },
] as const
export type LoginResourceType = typeof LoginResourceTypes[number]['value']

/**
 * 权限资源
 */
export interface LoginMenu {
  /** ID */
  id?: number
  /** 上级ID */
  parentId?: number
  /** 资源名称 */
  name?: string
  /** 资源编码 */
  code?: string
  /** 资源类型 */
  type: LoginResourceType
  /** 资源页面路径 */
  path?: string
  /** 资源图标 */
  icon?: string
  /** 是否可见 */
  visible?: boolean
  /** 子级资源 */
  children?: LoginMenu[]
}

export interface AuthAccountModifyPwdCmd {
  oldPwd?: string
  newPwd?: string
  confirmPwd?: string
}

export interface LoginTypeSettings {
  /** 登录方式 */
  loginType: string
  /** 登录方式的参数 */
  params: Record<string, string>
}

export interface LoginSettings {
  /** 是否开启注册 */
  registerEnable: boolean

  /** 登录方式参数 */
  loginTypeParams: Record<string, Record<string, string>>
}

export interface BindAccountCmd {
  loginType?: string
  thirdCode?: string
}

export interface UnbindAccountCmd {
  id: number
  loginType: string
}

const basePath = '/system/login'
export const loginApi = {
  login: useApi<LoginPwdReq, LoginUserInfo>(`${basePath}`).post,
  logout: useApi<null, null>(`${basePath}/logout`).post,
  getLoginInfo: useApi<null, LoginUserInfo>(`${basePath}/info`).get,
  queryLoginMenus: useApi<null, LoginMenu[]>(`${basePath}/menus`).get,
  getLoginAccount: (all?: boolean) => useApi<{ all?: boolean }, LoginUserInfo>(`${basePath}/info`).get({ all }),
  modifyLoginUser: useApi<LoginUserModifyCmd, any>(`${basePath}/modify`).patch,
  modifyLoginPwd: useApi<AuthAccountModifyPwdCmd, any>(`${basePath}/modifyPwd`).post,
  queryLoginSettings: (redirectUri: string) => useApi<{ redirectUri: string }, LoginSettings>(`${basePath}/settings`).get({ redirectUri }),
  sendCaptcha: useApi<CaptchaSendCmd, any>(`${basePath}/sendCaptcha`).post,
  bindAccount: useApi<BindAccountCmd, any>(`${basePath}/bind`).post,
  unbindAccount: useApi<UnbindAccountCmd, any>(`${basePath}/unBind`).post,
}
